using System.Xml;
using MessageGateway;

namespace FilterComponents
{
    public delegate void OnSequenceTaggerEvent(XmlDocument msg, int counter);

	public class SequenceTaggerComponent : SimpleFilter
	{
		private int counter = 1;
		private string parentXPath;
		private string toAdd;
        protected OnSequenceTaggerEvent taggerEvent;


		public SequenceTaggerComponent(IMessageReceiver receiver, IMessageSender sender, string xpath) : base (receiver, sender)
		{
			int lastSlash = xpath.LastIndexOf("/");
			parentXPath = xpath.Substring(0, lastSlash);
			toAdd = xpath.Substring(lastSlash + 1);
            taggerEvent = new OnSequenceTaggerEvent(NullEvent);
		}

        public SequenceTaggerComponent(string inputQueue, string outputQueue, string xpath, IMessageGatewayFactory factory) :
            this(factory.GetReceiverInstance(inputQueue), factory.GetSenderInstance(outputQueue), xpath)
        {}

		protected override void OnMessage(XmlDocument msg)
		{
			output.Send(addSequenceNumber(msg));
            taggerEvent(msg, counter - 1);
        }

        public void AddEventHandler(OnSequenceTaggerEvent handler)
        {
            taggerEvent += handler;
        }

        private void NullEvent(XmlDocument message, int numSplits){}

		private XmlDocument addSequenceNumber(XmlDocument msg)
		{
			XmlNode parent = msg.SelectSingleNode(parentXPath);
			if (toAdd.StartsWith("@"))
			{
				XmlAttribute att = msg.CreateAttribute(toAdd.Substring(1));
				att.Value = nextNumber();
				parent.Attributes.Append(att);
			}
			else
			{
				XmlElement element = msg.CreateElement("seqno");
				element.InnerText = nextNumber();
				parent.AppendChild(element);
			}
			return msg;
		}

		private string nextNumber()
		{
			return (counter++).ToString();
		}
	}

}